#include <stdio.h>
#include "linkedlist_getNthNode.h"

#define NUMELEMENT 10

NODE* getNthNodeFromLast(NODE* head, int positionToLast) {
    NODE* currentNode = head;    
    for (int i = 0; i < positionToLast; i ++) {
        if (currentNode->next != NULL) {
            currentNode = currentNode->next;
        }
        else {
            return NULL;
        }            
    }
    
    NODE* firstPointer = head;    
    while (currentNode != NULL) {
        firstPointer = firstPointer->next;
        currentNode = currentNode->next;
    }
    return firstPointer;
}

void test_linklist_getNthNode() {
	NODE* head = NULL;
	int data[NUMELEMENT] = {1, 3, 4, 1, 8, 6, 10, 3, 0, 1};
	
	for (int i = 0; i < NUMELEMENT; i++ ) {
		printf("Insert %d at the front of the list\n", data[i]);
		insertInFront(&head, data[i]);
	}
	
	printf("\nTraversing the list\n");
	traverseList(head);
	printf("\n");
	
	int Nth = 3;
	NODE* tmp = getNthNodeFromLast(head, Nth);
	printf("The %dth node from the last node contains data %d.\n", Nth, tmp->data);
	printf("\n");	
}
